import React, { useEffect, useState } from 'react';
import { Modal, Tree, message } from 'antd';
import type { TreeProps } from 'antd';
import type { IMenu, IRoleMenuAuth } from '../types/role';
import http from '../api/http';

interface Props {
  isOpen: boolean;
  roleId: number;
  onClose: () => void;
  onSuccess: () => void;
}

// 接口返回的权限对象类型
interface IAuthorityItem {
  authId: number;
  roleID: number;
  menuID: number; // 菜单ID
  menuName: string;
  sort: number;
  lastTime: string;
  parentId: number;
}

// 构建树形结构（基于parentId关联）
const buildMenuTree = (menus: IMenu[]): TreeProps['treeData'] => {
  const findChildren = (parentId: number): TreeProps['treeData'] => {
    return menus
      .filter(menu => menu.parentId === parentId)
      .map(menu => {
        const children = findChildren(menu.menuId);
        return {
          title: menu.menuName,
          key: menu.menuId.toString(),
          isFirstLevel: parentId === 0, // 一级菜单标识
          menuInfo: menu,
          children: children.length ? children : undefined,
          // 新增：保存所有子节点的key（用于计算半选状态）
          allSubKeys: children.length ? getAllSubKeys({ key: menu.menuId.toString(), children }) : []
        };
      });
  };
  return findChildren(0);
};

// 递归获取所有子菜单key（包括所有层级）
const getAllSubKeys = (node: TreeProps['treeData'][0]): string[] => {
  let subKeys: string[] = [];
  if (node.children?.length) {
    node.children.forEach(child => {
      subKeys.push(child.key);
      subKeys = [...subKeys, ...getAllSubKeys(child)];
    });
  }
  return subKeys;
};

// 获取所有一级菜单key
const getFirstLevelKeys = (treeData: TreeProps['treeData']): string[] => {
  return treeData.filter(node => node.isFirstLevel).map(node => node.key);
};

// 递归计算半选节点（一级菜单）
const getHalfCheckedFirstLevelKeys = (
  treeData: TreeProps['treeData'],
  checkedKeys: string[]
): string[] => {
  const halfCheckedKeys: string[] = [];
  
  const checkNode = (nodes: TreeProps['treeData']) => {
    nodes.forEach(node => {
      if (node.isFirstLevel) {
        // 一级菜单：判断是否半选
        const isChecked = checkedKeys.includes(node.key);
        const allSubKeys = node.allSubKeys || [];
        const checkedSubKeys = allSubKeys.filter(key => checkedKeys.includes(key));
        
        // 半选条件：未完全勾选，但有部分子节点勾选
        if (!isChecked && checkedSubKeys.length > 0 && checkedSubKeys.length < allSubKeys.length) {
          halfCheckedKeys.push(node.key);
        }
      }
      
      // 递归检查子节点
      if (node.children?.length) {
        checkNode(node.children);
      }
    });
  };
  
  checkNode(treeData);
  return halfCheckedKeys;
};

const RoleAuthModal: React.FC<Props> = ({ isOpen, roleId, onClose, onSuccess }) => {
  const [menuTreeData, setMenuTreeData] = useState<TreeProps['treeData']>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [firstLevelKeys, setFirstLevelKeys] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [isInitialLoad, setIsInitialLoad] = useState(true);

  // 加载数据：先获取菜单树，再获取角色权限
  useEffect(() => {
    if (isOpen && roleId) {
      setIsInitialLoad(false);
      
      Promise.all([
        http.get<IMenu[]>('Menus/All'),
        http.get<IAuthorityItem[]>('Authority', { rid: roleId })
      ])
        .then(([menusRes, authRes]) => {
          const treeData = buildMenuTree(menusRes.data);
          setMenuTreeData(treeData);
          setFirstLevelKeys(getFirstLevelKeys(treeData));
          setExpandedKeys(getFirstLevelKeys(treeData));

          const menuIds = authRes.data.filter(n=>n.parentId!=0)
            .map(item => item.menuID)
            .filter(id => typeof id === 'number');
          setCheckedKeys(menuIds.map(id => id.toString()));
        })
        .catch(err => {
          message.error('获取数据失败');
          console.error(err);
        });
    } else if (!isOpen) {
      setMenuTreeData([]);
      setCheckedKeys([]);
      setExpandedKeys([]);
      setFirstLevelKeys([]);
      setIsInitialLoad(true);
    }
  }, [isOpen, roleId]);

  // 处理菜单勾选
  const handleCheck = (checkedKeys: string[], { node }: { node: TreeProps['treeData'][0] }) => {
    if (node.isFirstLevel) {
      const allSubKeys = getAllSubKeys(node);
      const isChecked = checkedKeys.includes(node.key);

      if (isChecked) {
        const newChecked = [...new Set([...checkedKeys, ...allSubKeys])];
        setCheckedKeys(newChecked);
      } else {
        const newChecked = checkedKeys
          .filter(key => key !== node.key)
          .filter(key => !allSubKeys.includes(key));
        setCheckedKeys(newChecked);
      }
    } else {
      setCheckedKeys(checkedKeys);
    }
  };

  // 展开/折叠子菜单
  const handleExpand = (expandedKeys: string[]) => {
    setExpandedKeys(expandedKeys);
  };

  // 保存授权：通过计算获取半选主菜单ID
  const handleSaveAuth = async () => {
    setLoading(true);
    try {
      // 1. 计算半选的一级菜单key
      const halfCheckedKeys = getHalfCheckedFirstLevelKeys(menuTreeData, checkedKeys);
      
      // 2. 合并：原有选中key + 半选主菜单key（去重）
      const finalCheckedKeys = [...new Set([...checkedKeys, ...halfCheckedKeys])];
      
      // 3. 转换为数字ID
      const menuIds = finalCheckedKeys.map(key => Number(key));

      const params: IRoleMenuAuth = { roleId, menuIds };
      const res = await http.post('Authority', params);
      if (res.code === '1') {
       
        onClose();
        onSuccess();
      }
    } catch (err) {
      message.error('授权失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={isInitialLoad ? "角色授权" : `角色授权（ID：${roleId}）`}
      open={isOpen}
      onCancel={onClose}
      onOk={handleSaveAuth}
      confirmLoading={loading}
      width={500}
    >
      <div style={{ maxHeight: 400, overflowY: 'auto' }}>
        <Tree
          checkable
          treeData={menuTreeData}
          checkedKeys={checkedKeys}
          expandedKeys={expandedKeys}
          onCheck={handleCheck}
          onExpand={handleExpand}
          checkStrictly={false}
          titleRender={(node) => (
            <span style={{ 
              fontWeight: node.isFirstLevel ? 'bold' : 'normal',
              color: node.isFirstLevel ? '#1890ff' : 'inherit'
            }}>
              {node.isFirstLevel ? `[一级菜单] ${node.title}` : node.title}
            </span>
          )}
          showLine
        />
      </div>
    </Modal>
  );
};

export { RoleAuthModal };